package com.thinkfit.jy.utils;

import android.content.Context;
import android.graphics.PixelFormat;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.serialport.SerialPortManager;

/**
 * 返回按钮（用于在第三方应用中返回本应用）
 */
public class BackButtonViewUtils implements View.OnTouchListener {

    private static BackButtonViewUtils backButtonViewUtils;
    WindowManager windowManager;
    Context mContext;
    boolean isFist = true;
    boolean isTounch = false;

    String activityName;
    View inflate;
    int screenWidth,width;
    int showType = 0;
    float posX,posY,curPosX,curPosY;
    WindowManager.LayoutParams layoutParams;

    ConstraintLayout clItem;
    ConstraintLayout clSmal;
    LinearLayout llItem;
    ImageView ivStop,ivPause;
    TextView tvTime,tvItemType,tvItem,tvItemUnit;
    float x,y;
    public static BackButtonViewUtils getInstance(){
        if(backButtonViewUtils == null){
            backButtonViewUtils = new BackButtonViewUtils();
        }
        return backButtonViewUtils;
    }

    public void setKillPackageName(String name){
        activityName = name;
    }

    public void initView(Context context){
        mContext = context;
        if(windowManager == null){
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }
        int language = DataManager.Companion.getInstance().getLanguage();
        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   language : "+language);
        BaseUtils.StaticParams.changeAppLanguage(context, language);

        if(inflate == null){
            inflate = LayoutInflater.from(context).inflate(R.layout.item_back_button, null);
            DisplayMetrics dm = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(dm);
            width = dm.widthPixels;         // 屏幕宽度（像素）
            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   width : "+width);
            float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
            screenWidth = (int) (width / density);  // 屏幕宽度(dp)

//            clItem.setOnTouchListener(this);

        }

        llItem = inflate.findViewById(R.id.ll_item);
        tvItemType = inflate.findViewById(R.id.tv_item_type);
        tvItem = inflate.findViewById(R.id.tv_item);
        tvItemUnit = inflate.findViewById(R.id.tv_item_unit);

        clSmal = inflate.findViewById(R.id.cl_smal);



        tvTime = inflate.findViewById(R.id.tv_time);
        ivStop = inflate.findViewById(R.id.iv_stop);
        ivPause = inflate.findViewById(R.id.iv_pause);
        clItem = inflate.findViewById(R.id.cl_item);
        clItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isTounch){
                    AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
                    alphaAnimation.setDuration(500);
                    alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            ShowSpeedViewUtils.getInstance().recoverAnimation();
                            clItem.clearAnimation();
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    clItem.startAnimation(alphaAnimation);

                }
            }
        });
        clSmal.setOnTouchListener(this);
        ivStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogViewUtils.getInstance().initView(mContext,false,DialogViewUtils.EXIT_SPORT);
            }
        });
        ivPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(EquipmentInfoUtils.getInstance().isPause()){
                    if(MotionDataUtils.getInstance().isRun()){
//                            initSpeedSlopEnabled(true);
                        pauseDevice();

                    }else {
                        if(DeviceTypeUtils.connectDeviceType() == 0){
                            BluetoothOrder.getInstance().startTreadmill();
                        }else {
                            SerialPortManager.getInstance().startRun();

                        }
//                            initSpeedSlopEnabled(false);

                    }

                }else {
                    if(MotionDataUtils.getInstance().isRun()){
                        DialogViewUtils.getInstance().initView(mContext,false,DialogViewUtils.EXIT_SPORT);
                    }else {
                        CountDownViewUtils.getInstance().initView(mContext,3);
                    }
//                    tvSetGoal.setText(mContext.getString(R.string.app_set_goal));
//                    mType = 0;
//                    mNum = 0;
                }
            }
        });
        initPause();

        if(layoutParams == null){
            layoutParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

            layoutParams.gravity = Gravity.LEFT| Gravity. TOP;
//            layoutParams.gravity = Gravity.TOP| Gravity. CENTER;
            layoutParams.y = dp2px(57);
            layoutParams.x = dp2px(80);
        }


        if(isFist){
            isFist = false;
            windowManager.addView(inflate,layoutParams);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }

    }

    public void showAnimation(Context context,int type){
        if(inflate == null){
            initView(context);
        }else {
            inflate.setVisibility(View.VISIBLE);
        }
        showType = type;
        setTypeItem();
        AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
        alphaAnimation.setDuration(500);
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
//                goneLayout();
                clItem.clearAnimation();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        clItem.startAnimation(alphaAnimation);
    }

    public void pauseDevice(){
        if(!(SerialPortManager.getInstance().isConnected() || BluetoothOrder.getInstance().isConnect())){
            System.out.println("ddddddddddddddddddddddd   未连接设备");
            return;
        }
        if(DeviceTypeUtils.connectDeviceType() == 0){//判断连接类型
            BluetoothOrder.getInstance().closeRxJavaClone();
            BluetoothOrder.getInstance().closeTreadmillStateDisposable();
            if(EquipmentInfoUtils.getInstance().isPause()){
                System.out.println("ddddddddddddddddddddddd   蓝牙通知设备暂停");
                if(DeviceTypeUtils.getInstance().isTreadmill()){
                    BluetoothOrder.getInstance().pauseTreadmill();
                }else {
                    BluetoothOrder.getInstance().bluetoothOrderWrite(BluetoothOrder.EQUIPMENT_PAUSE);
                }

            }

        }else {
            System.out.println("ddddddddddddddddddddddd   串口通知设备暂停");
            SerialPortManager.getInstance().pauseRun();
        }
    }

    public void setInfo(SerialPortManager.CurrentInfo info){
        if (inflate != null){
            String time = "";
            if(showType == 2){
                int hour = info.time / 3600;
                int minute = (info.time / 60) % 60;
                int second = info.time % 60;
                if (hour > 0) {
                    time = BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                } else {
                    time =  BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                }
            }
            switch (showType){
                case 1:
                    if(DeviceTypeUtils.getDeviceType() == 2){
                        tvItem.setText(Utils.getNewFloat(info.speed*0.1f));
                    }else {
                        tvItem.setText(Utils.getNewFloat(info.speed*0.01f));
                    }

                    break;
                case 2:
                    tvItem.setText(time);
                    break;
                case 3:
                    tvItem.setText(Utils.getNewFloat2(info.distance / 1000f));
                    break;
                case 4:
                    tvItem.setText(Utils.getNewFloat(info.kcal*0.1f));
                    break;

            }

        }

    }

    public void initPause(){
        if(inflate == null){
            return;
        }
       if(MotionDataUtils.getInstance().isPause() || MotionDataUtils.getInstance().isStop()){
           ivPause.setImageResource(R.drawable.img_black_start);
       } else {
           ivPause.setImageResource(R.drawable.img_black_pause);
       }
    }

    public void setTypeItem(){
        switch (showType){
            case 1:
                tvItemType.setText(mContext.getString(R.string.app_speed_txt));
                tvItemUnit.setText(mContext.getString(R.string.app_km_h));
                break;
            case 2:
                tvItemType.setText(mContext.getString(R.string.app_time));
                tvItemUnit.setText(mContext.getString(R.string.app_time_min_ss));
                break;
            case 3:
                tvItemType.setText(mContext.getString(R.string.app_distance_1));
                tvItemUnit.setText(mContext.getString(R.string.app_km));
                break;
            case 4:
                tvItemType.setText(mContext.getString(R.string.app_use_up));
                tvItemUnit.setText(mContext.getString(R.string.app_kcal));
                break;

        }
    }

    public void goneButton(){
        if(windowManager != null){
            if(inflate != null){
                inflate.setVisibility(View.GONE);
            }
        }

    }

    public void setInfo(String time){
        if (inflate != null){
            tvTime.setText(time);
        }

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                isTounch = true;
                posX = event.getRawX();
                posY = event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                curPosX = event.getRawX();
                curPosY = event.getRawY();
                x = curPosX - posX;
                y = curPosY - posY;
                posX = curPosX;
                posY = curPosY;
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa   curPosX : "+curPosX+"   curPosY  : "+curPosY+"   screenWidth : "+screenWidth);
                if(inflate != null){
                    layoutParams.y += Math.round(y);
                    layoutParams.x += Math.round(x);

                    //更新悬浮球控件位置
                    windowManager.updateViewLayout(inflate, layoutParams);
                }
                break;
            case MotionEvent.ACTION_UP:

                if(inflate != null){
//                    if(layoutParams.x < 0){
//                        layoutParams.x = 0;
//                    }else {
//                        layoutParams.x = width;
//                    }

//                    if(curPosX< 100  || curPosX >(width - 100)){
//                        ivBack.setVisibility(View.VISIBLE);
//                        clItem.setVisibility(View.GONE);
//                        if(curPosX< width/2 ){
//                            layoutParams.x = -(width/2);
//                        }else {
//                            layoutParams.x = width/2;
//                        }
//                    }else {
//                        ivBack.setVisibility(View.GONE);
//                        clItem.setVisibility(View.VISIBLE);
//                        layoutParams.y = 0;
//                    }

//                    if(curPosX< width/2 ){
//                        layoutParams.x = -(width/2);
//                    }else {
//                        layoutParams.x = width/2;
//                    }
//                    //更新悬浮球控件位置
//                    windowManager.updateViewLayout(inflate, layoutParams);
                }
                isTounch = false;
                break;
        }
        return false;
    }

    public void invaliView(){
        if(inflate != null){
            windowManager.removeView(inflate);
            isFist = true;
            windowManager = null;
            inflate = null;
        }
    }

    /**
     * dp2px
     */
    protected int dp2px(float dpValue) {
        float density = mContext.getResources().getDisplayMetrics().density;
        return (int) (dpValue * density + 0.5f);
    }
}
